import { login } from 'api/user'
const TOKEN_KEY='token'
const STORAGE_KEY ='user-info'
export default{
 namespaced:true,
 state:()=>({
	 // 用户 token
      token: uni.getStorageSync(TOKEN_KEY) || '',
      // 用户信息
      userInfo: uni.getStorageSync(STORAGE_KEY) || {}
 }),
 mutations:{
	 //保存Token 至vuex
	 setToken(state,token){
		 state.token=token
		 this.commit('user/saveToken')
	 },
	 //保存Token 至本地存储
	 saveToken(state){
		 uni.setStorage({
		 	key:TOKEN_KEY,
			data:state.token
		 })
	 },
	 //删除本地Token
	 removeToken(state){
	 		 state.token=''
			 this.commit('user/saveToken')
	 },
	  //保存userInfo 至vuex
	 setUserInfo(state,userInfo){
		 state.userInfo=userInfo
		this.commit('user/saveUserInfo')
	 },
	 //保存userInfo 至本地存储
	 saveUserInfo(state){
	 		 uni.setStorage({
	 		 	key:STORAGE_KEY ,
	 			data:state.userInfo
	 		 })
	 },
	 //删除本地用户信息
	 removeUserInfo(state){
	 		 state.userInfo={}
	 		this.commit('user/saveUserInfo')
	 }
	 
 },
 //actions中完成异步操作
 actions:{
	 //完成登录
	async login(context,userProfile){
		console.log(userProfile)
		 const userInfo = JSON.parse(userProfile.rawData)
		const { data:res } = await login({
			 signature:userProfile.signature,
			 iv:userProfile.iv,
			 nickName:userInfo.nickName,
			 gender:userInfo.gender,
			 city:userInfo.city,
			 province:userInfo.province,
			 avatarUrl:userInfo.avatarUrl
		 })
		this.commit('user/setToken',res.token)
		this.commit('user/setUserInfo',userInfo)
	 },
	 //退出登录
	 logout(context){
		 this.commit('user/removeToken')
		 this.commit('user/removeUserInfo')
	 },
	 //登录状态判定
	async isLogin(context){
		 if(context.state.token) return true
		 //如果用户未登录引导用户登录
		const [error,res] = await uni.showModal({
		 	title:'登录之后才可以进行后续操作',
			content:'立即跳转到登录页面？（登录后会自动返回当前页面哦~~）'
		 })
		 const { cancel,confirm } =res
		 if(confirm){
			 uni.navigateTo({ url:'/subpkg/pages/login-page/login-page' })
		 }
		 return false
	 }
 }
 }